package com.devilvan.betrice.component;

import com.devilvan.betrice.dto.BetriceSnapDto;
import com.devilvan.betrice.exception.BetriceException;
import com.devilvan.betrice.util.ExploreDriverUtil;
import lombok.NonNull;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Optional;

/**
 * @author Evad.Wu
 * @Description 屏幕截图 组件
 * @date 2022-09-15
 */
@Lazy
@Component
@SuppressWarnings("FieldMayBeFinal")
public class BetriceSnapComponenet {
    private ChromeDriver chromeDriver = null;

    /**
     * 屏幕截图
     *
     * @param betriceSnapDto 截图网站URL、坐标等必要参数
     */
    public void snapScreen(@NonNull BetriceSnapDto betriceSnapDto) {
        Optional.of(chromeDriver).orElseGet(ExploreDriverUtil::getChromeDriver);
        //获取页面高宽使用：return document.documentElement.scrollWidth
        Long width = (Long) ((JavascriptExecutor) chromeDriver).executeScript("return document.documentElement.scrollWidth");
        Long height = (Long) ((JavascriptExecutor) chromeDriver).executeScript("return document.documentElement.scrollHeight");
        Long windowHeight = betriceSnapDto.getHeight();
        // 这里的height一定是裁剪前完整截取的图片
        chromeDriver.manage().window().setSize(new org.openqa.selenium.Dimension(width.intValue(), height.intValue()));
        //使用getScreenshotAs进行截取屏幕
        try {
            File srcFile = chromeDriver.getScreenshotAs(OutputType.FILE);
            BufferedImage image = ImageIO.read(srcFile);
            BufferedImage img = image.getSubimage(
                    betriceSnapDto.getXAxis().intValue(), betriceSnapDto.getYAxis().intValue(),
                    width.intValue(), windowHeight.intValue()
            );
            File file = new File(betriceSnapDto.getExportPath());
            if (!file.exists()) {
                boolean flag = file.mkdirs();
                if (!flag) {
                    throw new BetriceException("创建目录失败：" + file.getAbsolutePath());
                }
            }
            ImageIO.write(img, "png", file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
